package com.heima.media.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.IWmChannelService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * 频道信息表 servce实现类
 */
@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements IWmChannelService {

    /**
     * 根据频道列表模糊查询
     *
     * @param channelDto
     * @return
     */
    @Override
    public ResponseResult listByName(ChannelDto channelDto) {
        //1.构建分页查询对象
        Page<WmChannel> page = new Page<>(channelDto.getPage(), channelDto.getSize());

        //2.构建查询条件对象
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNoneBlank(channelDto.getName())) {
            queryWrapper.like(WmChannel::getName, channelDto.getName());

        }
        //3.执行分页查询方法
        this.page(page, queryWrapper);

        //模拟异常
       // int i = 1 /0 ;

        //4.封装分页返回结果
        PageResponseResult responseResult = new PageResponseResult();
        responseResult.setCurrentPage(channelDto.getPage()); //当前页
        responseResult.setSize(channelDto.getSize()); //页大小
        responseResult.setTotal(page.getTotal());   //总条数
        responseResult.setData(page.getRecords());  //模糊查询数据

        return responseResult;
    }

    /**
     * 保存频道名称
     *
     * @param channel
     * @return
     */
    @Override
    public ResponseResult saveName(WmChannel channel) {

        //1.构建查询条件对象
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        //1.1 查询频道名称是否重复
        queryWrapper.eq(WmChannel::getName, channel.getName());



        int count = this.count(queryWrapper);
        if (count == 0) {
            //说明频道名称不重复
            channel.setIsDefault(false); // 设置是否默认
            channel.setStatus(false); //设置排序
            channel.setOrd(0); // 设置排序

            this.save(channel);

            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }

    }

    /**
     * 查询正常状态的列表
     * @return
     */
    @Override
    public List<WmChannel> listBystatus() {
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmChannel::getStatus,1);
        List<WmChannel> list = this.list(queryWrapper);
        return list;
    }
}
